package com.example.controller;

import com.example.common.ExcelUtil;
import com.example.common.Result;
import com.example.entity.Stockorders;
import com.example.service.StockordersService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
@RequestMapping("/stockorders")
public class StockordersController {

    @Resource
    private StockordersService stockordersService;


    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        try {
            // 调用服务层方法获取数据
            List<LinkedHashMap<String, Object>> list = stockordersService.getExportData();

            // 检查数据是否为空
            if (list == null || list.isEmpty()) {
                throw new RuntimeException("数据为空，无法导出");
            }

            // 定义导出的文件名
            String filename = "Stockorders_" + System.currentTimeMillis() + ".xls";

            // 调用 Excel 工具类
            ExcelUtil.exportExcelUtil(response, list, filename);
        } catch (Exception e) {
            response.setStatus(500);
            response.getWriter().write("{\"code\":\"500\",\"msg\":\"导出失败：" + e.getMessage() + "\",\"data\":null}");
            e.printStackTrace();
        }
    }


    @PostMapping("/add")
    public Result add(@RequestBody Stockorders stockorders) {
        stockordersService.add(stockorders);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Stockorders stockorders) {
        stockordersService.update(stockorders);
        return Result.success();
    }

    @DeleteMapping("/deleteById/{id}")
    public Result delete(@PathVariable Integer id) {
        stockordersService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll(Stockorders stockorders) {
        List<Stockorders> list = stockordersService.selectAll(stockorders);
        return Result.success(list);
    }

    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "5") Integer pageSize,
                             Stockorders stockorders) {
        PageInfo<Stockorders> info = stockordersService.selectPage(pageNum, pageSize, stockorders);
        return Result.success(info);
    }
}
